#include "bmppenciltool.h"
#include "bmpeditor.h"
#include "action_changepixel.h"

const char * BMPPencilTool::NAME = "Pencil";
const char * BMPPencilTool::getName(){return NAME;}

bool BMPPencilTool::pressedTool(const int & a_mouseButton)
{
	switch(a_mouseButton)
	{
	case SDL_BUTTON_LEFT:
	case SDL_BUTTON_RIGHT:
		BMPEditor* bmpe = (BMPEditor*)getContext();
		m_useColor = *(bmpe->getPallette()->getSelectedColorIndex(
			(a_mouseButton==SDL_BUTTON_LEFT)
				?BMPPalletteManager::COLOR_MAIN
				:BMPPalletteManager::COLOR_OFF));
		draggedTool(a_mouseButton);
		return true;
	}
	return false;
}

bool BMPPencilTool::releasedTool(const int & a_mouseButton)
{
	if(m_useColor != NOT_DRAWING)
	{
		m_useColor = NOT_DRAWING;
		// when the mouse is let-go-of, the draw event ends
		if(m_undo->getCurrentAction()->getName() == Action_ChangePixel::GETNAME())
		{
			Action_ChangePixel * change = (Action_ChangePixel *)m_undo->getCurrentAction();
			change->setCanBeAddedTo(false);
		}
		return true;
	}
	return false;
}
bool BMPPencilTool::draggedTool(const int & a_mouseButton)
{
	if(m_useColor != NOT_DRAWING)
	{
		BMPEditor* bmpe = (BMPEditor*)getContext();
		SRect bitmapArea(bmpe->getBMP()->getArea());
		SPoint pixel(m_tool.getMin());
		if(m_useColor >= 0 && bitmapArea.contains(pixel))
		{
			Action_ChangePixel change(bmpe->getBMP(), pixel, m_useColor);
			m_undo->addAction(change, true);
		}
		return true;
	}
	return false;
}

void BMPPencilTool::draw(SDL_Surface * a_surface)
{
	BMPEditor* bmpe = (BMPEditor*)getContext();
	Uint32 color = bmpe->getPallette()->getSelectedColor(
		BMPPalletteManager::COLOR_MAIN,a_surface->format);
	VSDL_drawRect(a_surface, &m_toolOnScreen, color, 1);
}